package com.ruoyi.system.service.impl;
import com.ruoyi.common.config.TencentSmsConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.system.service.ISmsService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService {

    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    /**
     * API相关
     */
    private static String URL ="sms.tencentcloudapi.com";
    private static final String REGION = "ap-guangzhou";

    @Autowired
    private TencentSmsConfig config;
//    @Value("${sms.tencent.sdkAppId}")
//    private String SMS_SDK_APP_ID;
//    @Value("${sms.tencent.templateId}")
//    private String TEMPLATE_ID;
//    @Value("${sms.tencent.signName}")
//    private String SIGN_NAME;

    private static SmsClient smsClient;

    /**
     * 短信验证码长度
     */
    private final Integer LENGTH = 4;
    /**
     * redis 缓存
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public String sendSms(String phone, String code) {

        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        Credential cred = new Credential(config.getSecretId(), config.getSecretKey());
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(URL);
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        //实例化 SMS 的 client 对象
        SmsClient smsClient = new SmsClient(cred, REGION, clientProfile);

        String[] phoneNumbers = {"+86" + phone};
        //生成随机验证码
        //final String code = generateCode();
        //加入数组
        String[] templateParams = {code};
        //实例请求，组装参数
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppId(config.getSdkAppId());
        sendSmsRequest.setTemplateId(config.getTemplateId());
        sendSmsRequest.setSignName(config.getSignName());
        //发送的手机号
        sendSmsRequest.setPhoneNumberSet(phoneNumbers);
        //发送的内容（验证码）
        sendSmsRequest.setTemplateParamSet(templateParams);
        try {
            //发送
            final SendSmsResponse sendSmsResponse = smsClient.SendSms(sendSmsRequest);
            log.info("短信发送成功：{}", sendSmsResponse.toString());
            //加入缓存
            redisTemplate.opsForValue().set(phone, code, Constants.SMS_EXPIRATION, TimeUnit.MINUTES);

            return "OK";
        } catch (TencentCloudSDKException e) {
            log.error("发送失败，或者剩余短信数量不足", e);
        }
        return "发送失败，或者剩余短信数量不足";
    }

    @Override
    public Boolean validationCode(String phone, String code) {
        final String data = (String) redisTemplate.opsForValue().get(phone);
        if (code.equals(data)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成随机的验证码
     *
     * @return
     */
    public String generateCode() {
        return RandomStringUtils.randomNumeric(LENGTH);
    }

}
